'''
Created on Jun 20, 2012

@author: thomas_dao
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util
import json
import logging
from google.appengine.ext import ndb
from app import article_async, board_async, note_async
from kid import jinja_lib
from datetime import datetime, timedelta, date
from google.appengine.ext.ndb import Cursor

class HomePageHandler(BaseHandler):
    @ndb.synctasklet
    def handle(self):
        # Get input
        next_curs = self.request.get('curs')
        start_curs = None
        logging.info('next start_curs' + next_curs)
        if next_curs is not None and next_curs is not "":
            start_curs = Cursor(urlsafe=next_curs)
        
        env = jinja_lib.jinja_environment()
        template = env.get_template('home.html')
        user_key = util.get_current_user_key()
        user = None
        notes = None
        if user_key:
            (user, notes, user_boards) = yield (user_key.get_async(), 
                                   note_async.get_all_async(user_key, projection=['article']),
                                   board_async.get_all(user_key))
        
        values = {}
        
        now = datetime.now()
        day = now.day
        week = now.isocalendar()[1]
        month = now.month
        year = now.year
        
        ((articles, cur, more)) = yield article_async.get_top_vote(day, week, month, year, start_cursor=start_curs)
        values['articles'] = yield util.ndb_to_list_async(articles, detail=["first_note", "author"])       
        values['articles_json'] = json.dumps(util.ndb_to_list(articles))
        values['cursor'] = None
        if cur:
            values['cursor'] = cur.urlsafe()
        values['more'] = more
        values['user'] = {}
        if user:
            bookmarkArticles = [x.article for x in notes]
            logging.info(notes)
            logging.info("bookmarkArticles")
            logging.info(bookmarkArticles)
            values['user'] = util.ndb_to_dict(user)
            values['bookmark_articles'] = json.dumps(util.ndb_to_list(bookmarkArticles))
            values['user_boards'] = user_boards
        
        self.response.out.write(template.render(values))
    @ndb.synctasklet
    def get(self):
        self.handle()
        
    @ndb.synctasklet
    def post(self):
        self.handle()
        
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()